package cn.com.api.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.api.service.StartOnLoadService;

/**
 * 短信发送
 */
@Service
public class SendMessageService {

	@Autowired
	private StartOnLoadService startOnLoadService;

	private Logger logger = Logger.getLogger(SendMessageService.class);

	public String account1 = ""; // startOnLoadService.dictionaryMap().get("MESSAGE_UNAME");
	public String pswd1 = ""; // startOnLoadService.dictionaryMap().get("MESSAGE_PASSWORD");
	public String url1 = ""; // startOnLoadService.dictionaryMap().get("MESSAGE_URL");

	public boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
	public String product = null;// 产品ID
	public String extno = null;// 扩展码

	/**
	 * 
	 * @param url
	 *            应用地址，类似于http://ip:port/msg/
	 * @param account
	 *            账号
	 * @param pswd
	 *            密码
	 * @param mobile
	 *            手机号码，多个号码使用","分割
	 * @param msg
	 *            短信内容
	 * @param needstatus
	 *            是否需要状态报告，需要true，不需要false
	 * @return 返回值定义参见HTTP协议文档
	 * @throws Exception
	 */
	public String send(String mobile, String msg) throws Exception {
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod();
		try {

			URI base = new URI(startOnLoadService.dictionaryMap().get("MESSAGE_URL"), false);
			method.setURI(new URI(base, "HttpSendSM", false));
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("account", startOnLoadService.dictionaryMap().get("MESSAGE_UNAME")),
					new NameValuePair("pswd", startOnLoadService.dictionaryMap().get("MESSAGE_PASSWORD")),
					new NameValuePair("mobile", mobile), new NameValuePair("needstatus", String.valueOf(needstatus)),
					new NameValuePair("msg", msg), new NameValuePair("product", product),
					new NameValuePair("extno", extno), });
			int result = client.executeMethod(method);
			if (result == HttpStatus.SC_OK) {
				InputStream in = method.getResponseBodyAsStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}

				return URLDecoder.decode(baos.toString(), "UTF-8");
			} else {
				logger.error("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
				throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
			}
		} finally {
			method.releaseConnection();
			// logger.info(method.releaseConnection());
		}

	}

	/**
	 * 
	 * @param url
	 *            应用地址，类似于http://ip:port/msg/
	 * @param account
	 *            账号
	 * @param pswd
	 *            密码
	 * @param mobile
	 *            手机号码，多个号码使用","分割
	 * @param msg
	 *            短信内容
	 * @param needstatus
	 *            是否需要状态报告，需要true，不需要false
	 * @return 返回值定义参见HTTP协议文档
	 * @throws Exception
	 */
	public Integer batchSend(String mobile, String msg) throws Exception {
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod();
		try {
			Map<String, String> params = startOnLoadService.dictionaryMap();
			for (Map.Entry<String, String> entry : params.entrySet()) {
				System.out.println("---------entry:key-" + entry.getKey() + ",value-" + entry.getValue());
			}

			URI base = new URI(startOnLoadService.dictionaryMap().get("MESSAGE_URL"), false);
			method.setURI(new URI(base, "HttpBatchSendSM", false));
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("account", startOnLoadService.dictionaryMap().get("MESSAGE_UNAME")),
					new NameValuePair("pswd", startOnLoadService.dictionaryMap().get("MESSAGE_PASSWORD")),
					new NameValuePair("mobile", mobile), new NameValuePair("needstatus", String.valueOf(needstatus)),
					new NameValuePair("msg", msg), new NameValuePair("product", product),
					new NameValuePair("extno", extno), });
			int result = client.executeMethod(method);
			if (result == HttpStatus.SC_OK) {
				InputStream in = method.getResponseBodyAsStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}
				System.out.println(URLDecoder.decode(baos.toString(), "UTF-8"));
				return 1;
			} else {
				logger.error("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
				throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
			}
		} finally {
			method.releaseConnection();
		}
	}

	public static void main(String[] args) {

		// TODO Auto-generated method stub
		// 测试账号 jiekou-clcs-01 密码Tch111222
		// int ran = Utils.sixRandomNum();
		// String url = "http://222.73.117.158/msg/";// 应用地址
		// String account = "jiekou-clcs-01";// 账号
		// String pswd = "Tch111222";// 密码
		// String mobile = "18610096044";//
		// args["18610096044"];//手机号码，多个号码使用","分割
		// String msg = "您好，您的验证码是" + ran;// 短信内容
		// boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
		// String product = null;// 产品ID
		// String extno = null;// 扩展码
		// try {
		// Integer returnString = batchSend(url, account);
		// System.out.println(returnString);
		// // TODO 处理返回值,参见HTTP协议文档
		// } catch (Exception e) {
		// // TODO 处理异常
		// e.printStackTrace();
		// }
	}

}
